/**
 * 设备信息管理工具
 * 统一 Electron 和 Web 环境下的设备标识生成和管理
 */

function createDeviceFingerprint(): string {
  if (typeof crypto !== "undefined" && crypto.randomUUID) {
    return crypto.randomUUID();
  }
  const timestamp = Date.now().toString(16);
  const rand = () => Math.random().toString(16).substring(2, 10);
  return `${rand()}${rand()}-${timestamp.substring(0, 4)}-${timestamp.substring(
    4,
    8
  )}-${rand()}-${rand()}`;
}

export function getDeviceFingerprint(): string {
  let fingerprint = localStorage.getItem("device_fingerprint");
  if (!fingerprint) {
    fingerprint = sessionStorage.getItem("device_fingerprint");
    if (!fingerprint) {
      fingerprint = createDeviceFingerprint();
      localStorage.setItem("device_fingerprint", fingerprint);
    } else {
      localStorage.setItem("device_fingerprint", fingerprint);
    }
  }
  return fingerprint;
}

function createClientMark(): string {
  let type = "Web";
  let platform = "unknown";
  let arch = "unknown";
  let version = "unknown";

  const isElectron =
    typeof process !== "undefined" &&
    (process as any).versions &&
    (process as any).versions.electron;

  if (isElectron) {
    type = "Client";
  }

  if (typeof navigator !== "undefined") {
    platform = navigator.platform || "unknown";
    arch =
      (navigator as any).deviceMemory !== undefined
        ? `${(navigator as any).deviceMemory}GB`
        : "unknown";

    if ((navigator as any).userAgentData) {
      const uaData = (navigator as any).userAgentData;
      version = Array.isArray(uaData.brands)
        ? uaData.brands[uaData.brands.length - 1].brand
        : uaData.platform || "unknown";
    } else {
      const ua = navigator.userAgent;
      const matches = ua.match(/(chrome|firefox|safari|edge|opera)\/(\d+)/i);
      version = matches ? `${matches[1]}/${matches[2]}` : "unknown";
    }
  }

  return `seller/${type}/${platform}/${arch}/${version}`;
}

export function getClientMark(): string {
  let clientMark = localStorage.getItem("client_mark");
  if (!clientMark) {
    clientMark = createClientMark();
    localStorage.setItem("client_mark", clientMark);
  }
  return clientMark;
}

export async function getDeviceInfo(): Promise<{
  X_Client_Mark: string;
  X_Device_Fingerprint: string;
}> {
  return {
    X_Client_Mark: getClientMark(),
    X_Device_Fingerprint: getDeviceFingerprint()
  };
}

export function clearDeviceInformation(): void {
  localStorage.removeItem("device_fingerprint");
  sessionStorage.removeItem("device_fingerprint");
  localStorage.removeItem("client_mark");
}
